<%@ page import="java.sql.*" %><%--
本页面负责用户投票，仅后端处理:
1.对应option的number加一
2.user_vote添加user_id和option_id(记录具体到某一个选项)
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    request.setCharacterEncoding("UTF-8");
    int optionId = Integer.parseInt(request.getParameter("id"));
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai", "root", "123456");
        Statement statement = connection.createStatement();/*("update vote_option set number=number+1 where id=?");*/
        if (statement.executeUpdate("update vote_option set number=number+1 where id=" + optionId) != 0) {
            System.out.println("投票成功!");
        } else {
            System.out.println("投票失败!");
        }
        int userId = Integer.parseInt(session.getAttribute("userId").toString());
        //因为userid和option都是int,所以直接用+连接，如果是varchar用单引号连接
        //等效于:INSERT INTO user_option (user_id,option_id) VALUES (xxx,x)
        String sql = "INSERT INTO user_option (user_id,option_id) VALUES (" + userId + "," + optionId + ")";
        System.out.println(sql);
        //使用executeUpdate不用execute，后者适合查询
        if (statement.executeUpdate(sql) != 0) {
            System.out.println("保存用户投票成功!");
        } else {
            System.out.println("保存用户投票失败!");
        }
        statement.close();
        connection.close();
    } catch (Exception e) {
        out.print(e.getMessage());
        e.printStackTrace();
    }

    //投票过后回到选择vote的页面而不是option
    response.sendRedirect("../userPage.jsp");

%>
</body>
</html>
